#include"test.hpp"

const int processnum = 5;



//先描述
class channel
{
public:
    channel(int cmdfd, int workerid, string &processname)
    :_cmdfd(cmdfd),
    _workerid(workerid),
    _processname(processname)
    {}
public:
    int _cmdfd;
    pid_t _workerid;
    string _processname;
};

void work()
{
    // read(0)
    while(1)
    {
        int cmdcode = 0;
        int n = read(0, &cmdcode, sizeof(int));
        if(n == sizeof(int))
        {
            //执行cmdcode码的任务
            cout<<"cmdcode: "<<cmdcode<<" "<<tasks.size()<<endl;
            if(cmdcode >= 0 && cmdcode < tasks.size())
                 tasks[cmdcode]();
        }
        if(n == 0) break;
        // sleep(1);
    }
}
//命名规范
//输入 const&
//输出 *
//输入输出 const&
void init(vector<channel> *ch)
{

    for(int i = 0; i < processnum; i++)
    {
        int pipefd[2];
        int n = pipe(pipefd);
        assert(n == 0);

        pid_t id = fork();
        if(id == 0)
        {
            close(pipefd[1]);
            dup2(pipefd[0], 0);
            close(pipefd[0]);
            // work(pipefd[0]);
            work();
            exit(0);
        }

        close(pipefd[0]);
        string name("process-"+to_string(i));
        ch->push_back(channel(pipefd[1], id, name));
    }
}


void test(const vector<channel> &ch)
{
   for(auto &e : ch)
    {
        cout<<e._processname<<" "<<e._cmdfd<<" "<<e._workerid<<endl;
    }
}



void ctrlwork(const vector<channel> &ch)
{

    for(int i = 1; i<=100; i++)
        {
            //1.选择任务
            int cmdcode = rand() % tasks.size();

            //2.选择进程
            int processpos = rand() % ch.size();

            cout<<"father say: cmdcode is "<<cmdcode<<" send to"<<ch[processpos]._processname<<endl;
            //3.发送任务
            write(ch[processpos]._cmdfd, &cmdcode, sizeof(cmdcode));
            sleep(1);
        }
}

void quit_process(const vector<channel> &channels)
{
    for(auto e:channels)  close(e._cmdfd);
    for(auto e:channels)  waitpid(e._workerid, nullptr, 0);
}


int main()
{
    //设计随机数种子
    srand(time(nullptr));

    //再组织
    vector<channel> channels;

    //1.初始化
    init(&channels);
    load_task(&tasks);

    //test
    //test(channels);

    //2.开始控制进程
    ctrlwork(channels);

    //3.清理退出
    quit_process(channels);
    // sleep(1000);
    return 0;
}